﻿using System;
using gcloud_voice;
using UnityEngine;

namespace GVoiceSdk.GCloudVoiceAgent
{
    public enum VoiceMode
    {
        Unknown = -1,
        RealTime = 0, // Abandoned
        Messages = 1, // voice message mode
        Translation = 2, // Abandoned
        RSTT = 3, // real-time speech to text mode
        HIGHQUALITY = 4, // Abandoned
        RSTS = 5 // Abandoned
    }

    public enum VoiceErrorRetCode
    {
        // Messages
        ApplyMessageKey = 1 // 申请语音消息key
    }

    public delegate void OnError(int errorCode, string errorMsg);

    public static class GCloudVoiceSDK
    {
        public static OnError onError;

        static GCloudVoiceSDK()
        {
            VoiceEngine = null;
        }

        public static IGCloudVoice VoiceEngine { get; private set; }

        public static bool Init(string appId, string appKey, string openID, string url)
        {
            try
            {
                VoiceEngine = IGCloudVoice.GCloudVoice.GetEngine();
                VoiceEngine.SetAppInfo(appId, appKey, openID);
                VoiceEngine.SetServerInfo(url);
                var ret = VoiceEngine.Init();
                if (ret == (int)GCloudVoiceErr.GCLOUD_VOICE_SUCC)
                {
                    OffLineVoiceAgent.Init(VoiceEngine);
                    RealTimeVoiceAgent.Init(VoiceEngine);
                    return true;
                }

                return false;
            }
            catch (Exception e)
            {
#if UNITY_EDITOR
                Debug.Log("GCloudVoiceSDK Init , exception := " + e.Message);
#else
                UnityEngine.Debug.LogError("GCloudVoiceSDK Init , exception := " + e.Message);
#endif
                return false;
            }
            //return true;
        }

        public static void SetAppInfo(string appId, string appKey, string openID)
        {
            if (VoiceEngine == null) return;

            var ret = VoiceEngine.SetAppInfo(appId, appKey, openID);
            Debug.Log("SetAppInfo:" + ret);
        }

        public static bool SetMode(GCloudVoiceMode gCloudVoiceMode)
        {
            if (VoiceEngine == null)
            {
                Debug.LogError("[C#] SetMode ==> GCloudVoiceSDK.VoiceEngine is null");
                return false;
            }

            var ret = VoiceEngine.SetMode(gCloudVoiceMode);
            Debug.Log("[C#] IGCloudVoice SetMode , mode := " + gCloudVoiceMode + " ret := " + ret);
            if (ret != (int)GCloudVoiceErr.GCLOUD_VOICE_SUCC)
                return false;
            return true;
        }

        public static bool CanUseMicrophone()
        {
            var ret = false;
            foreach (var device in Microphone.devices)
                if (device != null && !string.IsNullOrEmpty(device))
                    ret = true;

            return ret;
        }
    }
}